package net.cassite.daf4j.ds;

import net.cassite.daf4j.Condition;
import net.cassite.daf4j.IData;
import net.cassite.daf4j.IExpression;
import net.cassite.daf4j.PreResult;

/**
 * 对象Resolver,用于自动调用conditionResolver,expressionResolver,entityDataParser的方法
 *
 * @param <Context>      上下文
 * @param <BasicElement> 基本元素
 * @see ConditionResolver
 * @see ExpressionResolver
 * @see ParserPacket
 */
public class ObjectResolver<Context, BasicElement> {
        private ConditionResolver<Context, BasicElement> conditionResolver;
        private ExpressionResolver<Context, BasicElement> expressionResolver;
        private EntityDataParser<Context, BasicElement> entityDataParser;
        private ParserPacket<Context, BasicElement, ?> parserPacket;

        ObjectResolver(ConditionResolver<Context, BasicElement> conditionResolver,
                       ExpressionResolver<Context, BasicElement> expressionResolver,
                       ParserPacket<Context, BasicElement, ?> parserPacket) {
                this.conditionResolver = conditionResolver;
                this.expressionResolver = expressionResolver;
                this.entityDataParser = parserPacket.entityDataParser;
                this.parserPacket = parserPacket;
        }

        public BasicElement resolve(Context context, Object o) throws Exception {
                if (o instanceof Condition) {
                        return conditionResolver.resolve(context, (Condition) o);
                } else if (o instanceof IExpression) {
                        return expressionResolver.resolve(context, (IExpression) o);
                } else if (o instanceof IData) {
                        return entityDataParser.parseData(context, (IData<?>) o);
                } else if (o instanceof PreResult) {
                        return entityDataParser.parseQuery(context, (PreResult<?>) o, parserPacket);
                } else {
                        String s = o.getClass().getName();
                        if (s.startsWith("java.") || s.startsWith("javax.")) {
                                return entityDataParser.parsePlain(context, o);
                        } else {
                                return entityDataParser.parseEntity(context, o);
                        }
                }
        }

        public ConditionResolver<Context, BasicElement> getConditionResolver() {
                return conditionResolver;
        }

        public ExpressionResolver<Context, BasicElement> getExpressionResolver() {
                return expressionResolver;
        }

        public EntityDataParser<Context, BasicElement> getEntityDataParser() {
                return entityDataParser;
        }

        @SuppressWarnings("unchecked")
        public <DS> ParserPacket<Context, BasicElement, DS> getParserPacket() {
                return (ParserPacket<Context, BasicElement, DS>) parserPacket;
        }
}
